package com.tiancheng.trade.authserver.utils;

import org.bouncycastle.util.encoders.UrlBase64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @Author: kellen
 * @Description:
 * @Date: create in 2024/11/13 11:14
 */
public class AESUtils {
    private static final String KEY_AES = "AES";

    public AESUtils() {
    }

    private static Cipher buildCipher(String key, boolean encrypt) {
        if (key != null && key.length() == 16) {
            byte[] raw = key.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

            try {
                Cipher cipher = Cipher.getInstance("AES");
                if (encrypt) {
                    cipher.init(1, skeySpec);
                } else {
                    cipher.init(2, skeySpec);
                }

                return cipher;
            } catch (Exception var6) {
                throw new RuntimeException(var6);
            }
        } else {
            throw new IllegalArgumentException("key不满足条件");
        }
    }

    public static String encrypt(String data, String key) {
        Cipher cipher = buildCipher(key, true);

        byte[] encrypted;
        try {
            encrypted = cipher.doFinal(data.getBytes());
        } catch (Exception var5) {
            throw new RuntimeException(var5);
        }

        return new String(UrlBase64.encode(encrypted));
    }

    public static String decrypt(String data, String key) {
        Cipher cipher = buildCipher(key, false);
        byte[] encrypted1 = UrlBase64.decode(data.getBytes());

        byte[] original;
        try {
            original = cipher.doFinal(encrypted1);
        } catch (Exception var6) {
            throw new RuntimeException(var6);
        }

        return new String(original);
    }
}
